import { load, request, htmlToString } from '../common_node.js'
import {testContent, testSearch} from "../crawler.test.js";

const source = {
  "id": "free_book_js/10",
  "name": "笔下文学",
  "portalUrl": "http://www.xfuedu.org",
  "searchBaseUrl": "http://www.xfuedu.org",
  "bookBaseUrl": "http://www.xfuedu.org",
  "active": true
};


async function searchBook(keyword, pageNum) {
  function getBoolList($) {
    const bookArr = [];
    const liArr = $(".txt-list-row5:eq(0)").find('li');
    liArr.each(function (index, elem) {
      if (index !== 0) {
        let nameAndPath = $(this).find("span:eq(1) a");
        bookArr.push({
          name: nameAndPath.text(),
          author: $(this).find(".s4").text(),
          path: nameAndPath.attr("href"),
          sourceId: source.id
        });
      }
    })
    return bookArr;
  }

  let url = source.searchBaseUrl + '/ar.php?keyWord=' + keyword;
  const html = await (await request(url)).text();
  const doc = load(html);
  const bookArr = getBoolList(doc);

  return {
    size: bookArr.length,
    pageNum: 1,
    pages: 1,
    sourceId: source.id,
    keyword: keyword,
    bookList: bookArr
  };
}

async function bookDetails(path) {
  const html = await (await request(source.bookBaseUrl + path)).text();
  let $ = load(html);

  return {
    name: $("meta[property='og:novel:book_name']").attr('content'),
    author: $("meta[property='og:novel:author']").attr('content'),
    path: path,
    sourceId: source.id,
    intro: $("div.desc").text(),
    coverUrl: $("meta[property='og:image']").attr('content'),
    type: $("meta[property='og:novel:category']").attr('content'),
  };
}

async function bookCatalog(path) {
  const html = await (await request(source.bookBaseUrl + path)).text();
  const $ = load(html);
  const chapters = $('.section-list:eq(1) .book-item a');
  let index = 0;
  let catalog = [];
  chapters.each(function (i, elem) {
    const item = $(this);
    catalog.push({
      index: index++,
      title: item.text(),
      path: path.replace(source.bookBaseUrl, '') + item.attr("href")
    });
  });
  return catalog;
}

async function chapterContent(path) {
  const html = await (await request(source.bookBaseUrl + path)).text();
  const $ = load(html);
  //去掉 章节错误,点此举报
  $(".posterror").remove();
  let content = htmlToString($("#content").html());
  let next = $(".m-bottom-opt a:eq(2)");
  if (next.text().includes("下一页")) {
    content += await chapterContent(next.attr("href"));
  }
  return content;
}

await testSearch("重生", searchBook);

await testContent("/book/106040/", { bookDetails, bookCatalog, chapterContent })
//debugger;

